package com.sfilyh.servelt;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.sfilyh.util.FileUtil;


@WebServlet("/bz-admin/upload")
public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;       

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String filePrefix = getServletContext().getRealPath("/");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String filePath =  sdf.format(new Date())+File.separator;
		
		String newFileName = UUID.randomUUID().toString().replace("-", "");
		String fullName = null;
		
		FileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			List /* FileItem */ items = upload.parseRequest(request);
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();

			    if (item.isFormField()) {
			        //
			    } else {
			    	String suffix = item.getName().substring(item.getName().lastIndexOf("."));
			    	fullName = File.separator+"upload"+File.separator+filePath+newFileName+suffix; 
			    	FileUtil.createFile(item.getInputStream(),new File(filePrefix+fullName));
			    }
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		PrintWriter out = response.getWriter();
		out.write("{\"url\":\""+fullName.replaceAll(File.separator, "/")+"\", \"title\":\"图片描述\", \"state\":\"SUCCESS\"}");
		out.close();	
	}
	
}
